//token请求地址
let url = 'https://api.weixin.qq.com/cgi-bin/token'

let data = {
	grant_type: 'client_credential',
	appid: 'wx944b2f3111aaba4d',
	secret: 'f10d7b5d3696c2f51a23770fb1743688'
}
//云环境id
let env = 'cloud1-7gdmofgod6fd2d3a'

//数据库插入语句
let add = 'https://api.weixin.qq.com/tcb/databaseadd?access_token='
//数据库查询
let select = 'https://api.weixin.qq.com/tcb/databasequery?access_token='

let db = {
	gettoken(...args) {
		let [path] = args
		return new Promise((resovle, reject) => {
			wx.request({
				method: "GET",
				url,
				data,
				header: {
					'content-type': 'application/json',
				},
				success(res) {
					resovle(res.data.access_token)
				},
				fail(err) {
					//console.log(err)
					reject("GET请求错误")
				}
			})
		})
	
	},
	
	async execute(dataurl, query){
		let token = await this.gettoken()
		let url = dataurl+token
		let data = JSON.stringify({
			env,
			query
		})
		let data1 = await new Promise((resovle, reject) =>{
				wx.request({
					method: "POST",
					url,
					data,
					header: {
						'content-type': 'application/json',
						"Content-Type": "application/x-www-form-urlencoded",
					},
					success(res) {
						resovle(res)
					},
					fail(err) {
						//console.log(err)
						reject("POST请求错误")
					}
				})
			})
			if(data1.data.errcode==0){
				let arr = []
				for (var i = 0; i < 9; i++) {
					arr[i] = JSON.parse(data1.data.data[i])
				}
				return {
					status: 200,
					msg: 'success',
					data: arr
				}
			}else{
				return {
					status: 404,
					msg: 'fail',
					errmsg: data1.data.errcode
				}
			}
			
			
	}
}
module.exports = {
	db,
	add,
	select
}